package com.zhiwang.planet.mvvm.viewmodel.withdraw

import android.annotation.SuppressLint
import android.view.View
import android.widget.CheckedTextView
import android.widget.RadioGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.switchMap
import com.zhiwang.planet.R
import com.zhiwang.planet.di.ActivityScope
import com.zhiwang.planet.event.TabChangeEvent
import com.zhiwang.planet.mvvm.model.RestApi
import com.zhiwang.planet.mvvm.model.entity.UserDao
import com.zhiwang.planet.mvvm.model.request.NonsenseRequest
import com.zhiwang.planet.ui.my.withdraw.AliBindDialog
import com.zhiwang.planet.ui.my.withdraw.WithDrawAdapter
import com.zhiwang.planet.ui.my.withdraw.WxBindDialog
import com.zhiwang.planet.util.*
import com.zhiwang.planet.widget.SimpleDialogBuilder
import io.reactivex.functions.Action
import io.reactivex.functions.Consumer
import org.greenrobot.eventbus.EventBus
import javax.inject.Inject

@ActivityScope
class WithDrawViewModel @Inject constructor(var activty: AppCompatActivity, var restApi: RestApi, var userDao: UserDao) : ViewModel(), AliBindDialog.OnBindSuccessCallBack, WithDrawAdapter.OnItemSelectedListener {


    var balanceAmount = "0"

    /*余额*/
    val balance = MutableLiveData<String>()

    /*趣钻*/
    val diamond = MutableLiveData<String>()


    var zhifubaoBind = false

    var weixinBind = false

    var zhifubaoName = ""

    var weixinName = ""

    var userPhone = ""

    val checkedIndex = MutableLiveData<Int>()

    val checkedPosition = MutableLiveData<Int>(0)

    val withDrawAdapter = WithDrawAdapter().also { it.setOnItemSelectedListener(this@WithDrawViewModel) }

    var weixinBindQrCodeUrl = ""

    var activitySelected = MutableLiveData(true)

    val activity_exist = MutableLiveData(true)

    val restTimes = MutableLiveData<Int>()

    val bind_hint = checkedIndex.switchMap {
        if (it == 0) {
            if (weixinBind.not())
                MutableLiveData("请先绑定微信公众号")
            else MutableLiveData(weixinName)
        } else {
            if (zhifubaoBind.not())
                MutableLiveData<String>("请先绑定支付宝")
            else MutableLiveData<String>(zhifubaoName)
        }
    }

    val weixinList = arrayListOf<String>()

    val zhifubaoList = arrayListOf<String>()

    val hintVisible = MutableLiveData<Int>(View.VISIBLE)

    val withdrawCash = MutableLiveData<String>()

    val taskDesc = MutableLiveData<String>()

    val inviteDesc = MutableLiveData<String>()

    val taskProgress = MutableLiveData<Int>()

    val inviteProgress = MutableLiveData<Int>()

    val taskProgress1 = MutableLiveData<Int>()

    val inviteProgress1 = MutableLiveData<Int>()

    @SuppressLint("CheckResult")
    fun load() {

        val user = userDao.getFirstUser()
        val bindInfo = user.bindInfo
//        bindInfo.isWeiXinBind.apply { weixinBind = this }
        bindInfo.isAliBind.apply { zhifubaoBind = this }
        userPhone = user.phone
        zhifubaoName = bindInfo.aliAccountName
//        weixinName = bindInfo.weixinNickname

//        if (bindInfo.isWeiXinBind.not()) {
//            restApi.getWxBindCodeInfo(NonsenseRequest())
//                    .androidSchedule()
//                    .responseFunc()
//                    .subscribe({
//                        weixinBindQrCodeUrl = it.qrCodeUrl ?: ""
//                    }, {}, {})
//        }

        restApi.getWithDrawList("weixin")
                .arrange(Consumer {
                    weixinList.clear()
                    weixinList.addAll(it.dropWhile { it == "1" })
                    checkedPosition.value = 0
                    switch(0)
                })
        restApi.getWithDrawList("alipay")
                .arrange(Consumer {
                    zhifubaoList.clear()
                    zhifubaoList.addAll(it.dropWhile { it == "1" })
                })

        loadBalance()

        restApi.getWithdrawActivityInfo()
                .arrange(Consumer { it ->
                    restTimes.value = it.withdrawTime
                    taskProgress1.value = it.progress[0]
//                    inviteProgress1.value = it.progress[1]
                    taskProgress.value = (99 * it.progress[0] / 3f).toInt()
//                    inviteProgress.value = (100 * it.progress[1] / 2f).toInt()
                    taskDesc.value = it.desc[0]
//                    inviteDesc.value = it.desc[1]
                }, Consumer {
                    Toaster.message(it.message ?: "err")
                }, Action {

                })


    }

    fun loadBalance() {
        val user  = userDao.getFirstUser()

        balance.value = user.revenue
//        restApi.getDiamondAndBeanInfo(NonsenseRequest())
//                .arrange(Consumer {
//                    balanceAmount = it.diamond
//                    balance.value = String.format("%,.2f", it.diamond.toInt() / 10000f)
//                    diamond.value = String.format("%,d", it.diamond.toInt())
//                })
    }

    /*点击绑定*/
    fun bind() {

        if (checkedIndex.value == 0 && weixinBind.not()) {
            WxBindDialog.create(activty, weixinBindQrCodeUrl).show()
        } else if (checkedIndex.value == 1 && zhifubaoBind.not()) {
            AliBindDialog.create(activty, this, userPhone).show()
        }
    }


    /*选择活动提现*/
    fun selectActivity(v: View) {
        val checkBox = v.findViewById(R.id.cb_oneshot) as CheckedTextView
        if (checkedIndex.value == 1) {
//            Toasty.message("暂不支持支付宝1元提现")
            checkBox.isChecked = false
        } else {
            activitySelected.value = true
            withDrawAdapter.unselectAll()
        }
    }

    override fun onItemSelected(position: Int) {
        activitySelected.value = false
//        withDrawAdapter.unselectAll()
    }

    override fun onBindSuccess() {
        load()
    }

    fun onCheckedChange(group: RadioGroup, checkedId: Int) {
        val checkedPosition = group.indexOfChild(group.findViewById<View>(checkedId))
        switch(checkedPosition)
    }

    private fun switch(checkedPosition: Int) {
        withDrawAdapter.reset()
        checkedIndex.value = checkedPosition
        hintVisible.value = View.VISIBLE
        withDrawAdapter.setDatas(if (checkedIndex.value == 0) weixinList else zhifubaoList)
        if (activitySelected.value == true) { //一元提现
            if (checkedIndex.value == 1) //支付宝切换到 普通提现
                activitySelected.value = false
            else
                withDrawAdapter.unselectAll() //微信取消普通提现
        } else withDrawAdapter.reset()
    }

    fun withdraw() {
        val cash: String = if (activitySelected.value == true) {
            "1"
        } else {
            if (checkedIndex.value == 0)
                weixinList[withDrawAdapter.selectPos]
            else zhifubaoList[withDrawAdapter.selectPos]
        }

        if (checkCashEnough(cash))
            withdrawCash.value = cash
    }

    fun checkCashEnough(cash: String): Boolean {
        return if (balanceAmount.toInt() > cash.toInt())
            true
        else {
            SimpleDialogBuilder()
                    .title("申请提现失败")
                    .titleTextColor(R.color.colorPrimary)
                    .buttonText("我知道了")
                    .content("余额不足，加油哦！")
                    .build(activty)
                    .show()
            false
        }
    }

    fun navMoney() {
        EventBus.getDefault().post(TabChangeEvent(1))
        activty.suicideAfterTransition()
    }
}